#include <pcap.h>
#include "interface-pcap.h"

static pcap_t* pacp_handle = NULL;
static ppp_frame_hanler ppp_handler;
void defualt_pcap_callback(u_char* args, const struct pcap_pkthdr* pkthdr, const u_char *buffer);

int init_pcap_handle(char* dev_name, char* filter, ppp_frame_hanler frame_handler)
{    
    struct bpf_program bg;

    char err_buf[PCAP_ERRBUF_SIZE];
    pacp_handle = pcap_open_live( dev_name, 1000, 0, 1000, err_buf );
    if(!pacp_handle){
        fprintf(stderr, "Error in pcap_pcap_open_live: %s\n", err_buf);
        return 0;
    }

    if( !pcap_compile(pacp_handle, &bg, filter, 0, 0)){
        pcap_close(pacp_handle);
        return 0;
    }
    if(!pcap_setfilter(pacp_handle, &bg)){
        pcap_close(pacp_handle);
        return 0;
    }

    ppp_handler = frame_handler;
    return 1;
}

void release_pcap_handle()
{
    pcap_close(pacp_handle);
}

void list_all_dev()
{
    pcap_if_t *alldevs;
    pcap_if_t *device;
    char err_buf[PCAP_ERRBUF_SIZE];

    if(pcap_findalldevs(&alldevs, err_buf) == -1) {
        fprintf(stderr, "Error in pcap_findalldevs: %s\n", err_buf);
        return ;
    }
    device = alldevs;
    for( ; device != NULL; device = device->next) {
        printf("Device name: %s\n", device->name);
        printf("Description: %s\n", device->description);
    }
    pcap_freealldevs(alldevs);
    return;
}

void defualt_pcap_callback(u_char* args, const struct pcap_pkthdr* pkthdr, const u_char *buffer)
{
    ppp_handler(buffer);
}

void send_data(u_char* data, int length) {
        pcap_sendpacket(pacp_handle, data, length);
}

void begin_capture()
{
    pcap_loop(pacp_handle, -1, defualt_pcap_callback, NULL);
}

void end_capture()
{
    //do nothing
}

